# -*- coding: utf-8 -*-
"""ui_mixin
仅包含 GUI 组件（布局）相关的创建函数，便于把 main.py 的纯 UI 代码搬过来。

请将下列 6 个函数完整剪切粘贴到 UIMixin 类中：
  • check_tab_change
  • create_convert_widgets
  • create_split_widgets
  • create_merge_widgets
  • create_img_to_pdf_widgets
  • create_watermark_widgets
"""

import tkinter as tk
from tkinter import filedialog, messagebox, ttk
from tkinter.scrolledtext import ScrolledText
import customtkinter as ctk


class UIMixin:
    """窗口各标签页 UI 创建相关 mixin"""

    def check_tab_change(self):
        """定期检查标签页是否改变"""
        current_tab = self.tabview.get()
        if current_tab != self.last_tab:
            # 标签页发生改变
            if current_tab == "PDF转图片":
                self.geometry("700x650")
            elif current_tab == "PDF拆分":
                self.geometry("700x690")
            elif current_tab == "图片转PDF":
                self.geometry("700x660")
            elif current_tab == "PDF合并/尺寸统一":
                self.geometry("700x650")
            elif current_tab == "添加水印":  # 新增水印页面的大小调整
                self.geometry("760x770")  # 可能需要调整
            elif current_tab == "Word转PDF":  # 新增 Word ➜ PDF 页面
                self.geometry("700x650")  # 根据需要调整
            elif current_tab == "Excel转PDF":
                self.geometry("760x720")
            else:  # Default or other tabs
                self.geometry("700x650")  # Default back
            self.last_tab = current_tab

        # 继续监听
        self.after(100, self.check_tab_change)

    # ------------------------------------------------------------------
    # Excel ➜ PDF Widgets
    # ------------------------------------------------------------------

    def create_excel2pdf_widgets(self):
        """创建 Excel 批量转 PDF 控件 (WPS)"""
        self.tab_excel.grid_columnconfigure(0, weight=1)

        title = ctk.CTkLabel(self.tab_excel, text="Excel批量转PDF (WPS)", font=("微软雅黑", 24, "bold"))
        title.grid(row=0, column=0, pady=20)

        main_frame = ctk.CTkFrame(self.tab_excel)
        main_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        main_frame.grid_columnconfigure(0, weight=1)

        # 选择文件按钮
        ctk.CTkButton(main_frame, text="选择Excel文件(可多选)", command=self.select_excel_files, width=200).grid(row=0, column=0, pady=10)

        # 文件列表
        self.excel_file_listbox = ctk.CTkTextbox(main_frame, height=150, width=520)
        self.excel_file_listbox.grid(row=1, column=0, pady=10, padx=20)
        self.excel_file_listbox.configure(state="disabled")

        # 输出目录选择
        output_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
        output_frame.grid(row=2, column=0, sticky="ew", padx=20, pady=(0, 10))
        output_frame.grid_columnconfigure(1, weight=1)
        ctk.CTkLabel(output_frame, text="输出目录:").grid(row=0, column=0, sticky="w")
        self.excel_output_entry = ctk.CTkEntry(output_frame)
        self.excel_output_entry.grid(row=0, column=1, sticky="ew", padx=(5, 5))
        ctk.CTkButton(output_frame, text="选择", width=60, command=self.select_excel_output_folder).grid(row=0, column=2)

        # 导出设置框架
        settings = ctk.CTkFrame(main_frame)
        settings.grid(row=3, column=0, sticky="ew", padx=20, pady=10)
        settings.grid_columnconfigure(3, weight=1)

        # 页面方向
        self.excel_orientation = tk.StringVar(value="landscape")
        ctk.CTkLabel(settings, text="页面方向:").grid(row=0, column=0, sticky="w")
        ctk.CTkRadioButton(settings, text="横向", variable=self.excel_orientation, value="landscape").grid(row=0, column=1)
        ctk.CTkRadioButton(settings, text="纵向", variable=self.excel_orientation, value="portrait").grid(row=0, column=2)

        # 页面居中
        self.excel_center_h = tk.BooleanVar(value=True)
        self.excel_center_v = tk.BooleanVar(value=True)
        ctk.CTkCheckBox(settings, text="水平居中", variable=self.excel_center_h).grid(row=1, column=0, sticky="w", pady=5)
        ctk.CTkCheckBox(settings, text="垂直居中", variable=self.excel_center_v).grid(row=1, column=1, sticky="w", pady=5)

        # 缩放设置
        self.excel_fit_page = tk.BooleanVar(value=True)
        fit_checkbox = ctk.CTkCheckBox(settings, text="适应页面宽度", variable=self.excel_fit_page, command=self.toggle_excel_scale_entry)
        fit_checkbox.grid(row=2, column=0, sticky="w", pady=5)

        self.excel_scale = tk.IntVar(value=100)
        scale_frame = ctk.CTkFrame(settings, fg_color="transparent")
        scale_frame.grid(row=2, column=1, sticky="w", padx=(20, 0))
        ctk.CTkLabel(scale_frame, text="缩放比例:").grid(row=0, column=0)
        self.excel_scale_entry = ctk.CTkEntry(scale_frame, width=60, textvariable=self.excel_scale)
        self.excel_scale_entry.grid(row=0, column=1, padx=5)
        ctk.CTkLabel(scale_frame, text="%").grid(row=0, column=2)
        
        # 初始状态：勾选了适应页面宽度，禁用缩放比例输入
        self.excel_scale_entry.configure(state="disabled")

        # 进度条
        self.excel_progress_bar = ctk.CTkProgressBar(main_frame)
        self.excel_progress_bar.grid(row=4, column=0, pady=10, padx=20, sticky="ew")
        self.excel_progress_bar.set(0)

        # 状态
        self.excel_status_label = ctk.CTkLabel(main_frame, text="准备就绪")
        self.excel_status_label.grid(row=5, column=0, pady=5)

        # 开始按钮
        self.excel_convert_btn = ctk.CTkButton(main_frame, text="开始转换", width=200, command=self.start_excel2pdf_conversion)
        self.excel_convert_btn.grid(row=6, column=0, pady=20)

    def toggle_excel_scale_entry(self):
        """切换缩放比例输入框的启用状态"""
        if self.excel_fit_page.get():
            # 勾选了适应页面宽度，禁用缩放比例
            self.excel_scale_entry.configure(state="disabled")
        else:
            # 未勾选适应页面宽度，启用缩放比例
            self.excel_scale_entry.configure(state="normal")

    def create_convert_widgets(self):
        # 配置列权重，使内容居中
        self.tab_convert.grid_columnconfigure(0, weight=1)

        # 标题
        self.title_label = ctk.CTkLabel(
            self.tab_convert,
            text="PDF批量转图片",
            font=("微软雅黑", 24, "bold")
        )
        self.title_label.grid(row=0, column=0, pady=20)

        # 创建一个主框架来包含所有控件，实现居中效果
        main_frame = ctk.CTkFrame(self.tab_convert)
        main_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        main_frame.grid_columnconfigure(0, weight=1)

        # 选择文件按钮
        self.select_file_btn = ctk.CTkButton(
            main_frame,
            text="选择PDF文件(可多选)",
            command=self.select_pdfs,
            width=200  # 设置固定宽度
        )
        self.select_file_btn.grid(row=0, column=0, pady=10)

        # 选择输出路径按钮
        self.select_output_btn = ctk.CTkButton(
            main_frame,
            text="选择输出文件夹",
            command=self.select_output_folder,
            width=200  # 设置固定宽度
        )
        self.select_output_btn.grid(row=1, column=0, pady=10)

        # 文件列表框
        self.file_listbox = ctk.CTkTextbox(
            main_frame,
            height=150,
            width=500
        )
        self.file_listbox.grid(row=2, column=0, pady=10, padx=20)

        # 输出方式选择框架
        self.output_mode_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
        self.output_mode_frame.grid(row=3, column=0, pady=10, padx=20, sticky="ew")
        
        # 创建输出模式变量
        self.output_mode = tk.StringVar(value="separate")  # 默认分类存储
        
        ctk.CTkLabel(self.output_mode_frame, text="输出方式：").pack(side=tk.LEFT, padx=(0, 10))
        ctk.CTkRadioButton(
            self.output_mode_frame,
            text="每个PDF单独创建文件夹分类",
            variable=self.output_mode,
            value="separate"
        ).pack(side=tk.LEFT, padx=10)
        ctk.CTkRadioButton(
            self.output_mode_frame,
            text="所有图片放入同一个文件夹",
            variable=self.output_mode,
            value="single_folder"
        ).pack(side=tk.LEFT, padx=10)

        # 质量调整框架
        self.quality_frame = ctk.CTkFrame(main_frame)
        self.quality_frame.grid(row=4, column=0, pady=10, padx=20, sticky="ew")
        self.quality_frame.grid_columnconfigure(1, weight=1)

        # 质量标签
        self.quality_label = ctk.CTkLabel(
            self.quality_frame,
            text=f"图片质量(正常300即可，越高越清晰): {self.quality}"
        )
        self.quality_label.grid(row=0, column=0, padx=10)

        # 质量调整滑块
        self.quality_slider = ctk.CTkSlider(
            self.quality_frame,
            from_=72,
            to=600,
            number_of_steps=44,
            command=self.update_quality,
            width=200  # 设置固定宽度
        )
        self.quality_slider.grid(row=0, column=1, padx=10)
        self.quality_slider.set(300)

        # 进度条
        self.progress_bar = ctk.CTkProgressBar(main_frame)
        self.progress_bar.grid(row=5, column=0, pady=10, padx=20, sticky="ew")
        self.progress_bar.set(0)

        # 状态标签
        self.status_label = ctk.CTkLabel(
            main_frame,
            text="准备就绪"
        )
        self.status_label.grid(row=6, column=0, pady=5)

        # 转换按钮
        self.convert_btn = ctk.CTkButton(
            main_frame,
            text="开始转换",
            command=self.start_conversion,
            width=200  # 设置固定宽度
        )
        self.convert_btn.grid(row=7, column=0, pady=20)

    def create_split_widgets(self):
        """创建PDF拆分页面的控件"""
        # 使主框架可以扩展
        self.tab_split.grid_rowconfigure(1, weight=1)
        self.tab_split.grid_columnconfigure(0, weight=1)

        # 标题
        self.split_title = ctk.CTkLabel(
            self.tab_split,
            text="PDF批量拆分",
            font=("微软雅黑", 24, "bold")
        )
        self.split_title.grid(row=0, column=0, pady=20, sticky="n")

        # 内容框架 (所有控件组将放置在此框架的网格中)
        content_frame = ctk.CTkFrame(self.tab_split)
        content_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        content_frame.grid_columnconfigure(0, weight=1)  # Allow content frame to expand horizontally
        # Configure rows: Listbox expands most, others fixed or minimal expansion
        content_frame.grid_rowconfigure(1, weight=1)  # Listbox row expands
        content_frame.grid_rowconfigure(2, weight=0)  # Options row
        content_frame.grid_rowconfigure(3, weight=0)  # Output Dir row
        content_frame.grid_rowconfigure(4, weight=0)  # Output Suffix row
        content_frame.grid_rowconfigure(5, weight=0)  # Progress row
        content_frame.grid_rowconfigure(6, weight=0)  # Status row
        content_frame.grid_rowconfigure(7, weight=0)  # Button row

        # --- Row 0: 选择文件按钮 ---
        ctk.CTkButton(content_frame, text="选择PDF文件(可多选)", command=self.browse_split_files, width=200).grid(
            row=0, column=0, pady=(5, 10))  # Center button

        # --- Row 1: 文件列表框 ---
        self.split_file_listbox = ctk.CTkTextbox(content_frame)
        self.split_file_listbox.grid(row=1, column=0, padx=5, pady=5, sticky="nsew")

        # --- Row 2: 选项 (页面范围和每页拆分) ---
        # Group widgets for this row in a transparent frame
        options_group_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
        options_group_frame.grid(row=2, column=0, pady=(5, 0), padx=5, sticky="ew")
        options_group_frame.grid_columnconfigure(1, weight=1)  # Allow entry to expand

        ctk.CTkLabel(options_group_frame, text="页面范围：").grid(row=0, column=0, padx=(0, 5), sticky="w")
        self.range_entry = ctk.CTkEntry(options_group_frame, placeholder_text="例如: 1-5 6-7 8-10 (空格分隔多个范围，每个范围生成一个PDF)")
        self.range_entry.grid(row=0, column=1, sticky="ew")

        self.split_each_page_var = tk.BooleanVar(value=False)
        self.split_each_page_checkbox = ctk.CTkCheckBox(
            options_group_frame,
            text="每一页都拆分",
            variable=self.split_each_page_var,
            command=self.toggle_range_entry
        )
        self.split_each_page_checkbox.grid(row=0, column=2, padx=(10, 0), sticky="w")

        # --- Row 3: 输出目录 ---
        # Group widgets for this row in a transparent frame
        output_dir_group_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
        output_dir_group_frame.grid(row=3, column=0, pady=(5, 0), padx=5, sticky="ew")
        output_dir_group_frame.grid_columnconfigure(1, weight=1)  # Allow entry to expand

        ctk.CTkLabel(output_dir_group_frame, text="输出目录：").grid(row=0, column=0, padx=(0, 5), pady=5, sticky="w")
        self.split_output_path = tk.StringVar()
        output_entry = ctk.CTkEntry(output_dir_group_frame, textvariable=self.split_output_path)
        output_entry.grid(row=0, column=1, padx=(0, 5), pady=5, sticky="ew")
        ctk.CTkButton(output_dir_group_frame, text="选择", command=self.browse_split_output, width=60).grid(
            row=0, column=2, pady=5, sticky="e")

        # --- Row 4: 输出后缀 ---
        # Group widgets for this row in a transparent frame
        output_suffix_group_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
        output_suffix_group_frame.grid(row=4, column=0, pady=(5, 0), padx=5, sticky="ew")
        output_suffix_group_frame.grid_columnconfigure(1, weight=1)  # Allow entry to expand

        ctk.CTkLabel(output_suffix_group_frame, text="输出后缀：").grid(row=0, column=0, padx=(0, 5), pady=5, sticky="w")
        self.output_name_entry = ctk.CTkEntry(output_suffix_group_frame, placeholder_text="留空则覆盖范围文件")
        self.output_name_entry.grid(row=0, column=1, columnspan=2, padx=(0, 5), pady=5,
                                    sticky="ew")  # Span 2 cols in group frame
        self.output_name_entry.insert(0, "_拆分")

        # --- Row 5: 进度条 ---
        self.split_progress = ctk.CTkProgressBar(content_frame)
        self.split_progress.grid(row=5, column=0, padx=5, pady=(10, 2), sticky="ew")
        self.split_progress.set(0)

        # --- Row 6: 状态标签 ---
        self.split_status = ctk.CTkLabel(content_frame, text="准备就绪")
        self.split_status.grid(row=6, column=0, padx=5, pady=2, sticky="ew")

        # --- Row 7: 操作按钮 ---
        self.split_btn = ctk.CTkButton(
            content_frame,
            text="开始拆分",
            command=self.start_split_pdf,
            width=200
        )
        self.split_btn.grid(row=7, column=0, pady=20)  # Center button

    def create_merge_widgets(self):
        """创建PDF合并页面的控件"""
        # 使主框架和列表框可扩展
        self.tab_merge.grid_rowconfigure(1, weight=1)
        self.tab_merge.grid_columnconfigure(0, weight=1)

        # 标题
        self.merge_title = ctk.CTkLabel(
            self.tab_merge,
            text="PDF合并/尺寸统一",
            font=("微软雅黑", 24, "bold")
        )
        self.merge_title.grid(row=0, column=0, pady=20, sticky="n")

        # 内容框架 (所有控件将放置在此框架的网格中)
        content_frame = ctk.CTkFrame(self.tab_merge)
        content_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        # Configure columns: listbox expands, button column fixed
        content_frame.grid_columnconfigure(0, weight=1)
        content_frame.grid_columnconfigure(1, weight=0)
        # Configure rows: listbox expands most, others fixed or minimal expansion
        content_frame.grid_rowconfigure(0, weight=3)  # Listbox row expands
        content_frame.grid_rowconfigure(1, weight=0)  # Size options row
        content_frame.grid_rowconfigure(2, weight=0)  # Output row
        content_frame.grid_rowconfigure(3, weight=0)  # Status row
        content_frame.grid_rowconfigure(4, weight=0)  # Button row

        # --- Row 0: 文件列表与操作按钮 ---
        self.file_list_text = ctk.CTkTextbox(content_frame)
        self.file_list_text.grid(row=0, column=0, padx=5, pady=5, sticky="nsew")  # Listbox in col 0
        self.file_list_text.configure(state="disabled")

        # 文件操作按钮区域 (垂直排列在列表右侧)
        button_frame = ctk.CTkFrame(content_frame)  # Keep this inner frame for vertical button layout
        button_frame.grid(row=0, column=1, padx=5, pady=5, sticky="ns")  # Buttons in col 1

        action_buttons = [
            ("添加文件", self.add_merge_file),
            # ("添加文件夹", self.add_merge_folder), # REMOVED
            ("删除选中", self.remove_selected_item),
            ("上移选中", self.move_item_up),
            ("下移选中", self.move_item_down),
            ("清空列表", self.clear_merge_list)
        ]
        for i, (text, command) in enumerate(action_buttons):
            ctk.CTkButton(
                button_frame, text=text, command=command, width=80
            ).pack(padx=5, pady=3, fill=tk.X)

        # --- Row 1: 统一页面大小选项 ---
        # Use a transparent inner frame to manage packing within the grid row
        size_option_outer_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
        size_option_outer_frame.grid(row=1, column=0, columnspan=2, pady=10, padx=5, sticky="ew")

        self.uniform_size_var = tk.BooleanVar(value=False)
        self.uniform_size_checkbox = ctk.CTkCheckBox(
            size_option_outer_frame,
            text="统一页面大小:",
            variable=self.uniform_size_var,
            command=self.toggle_size_options_visibility
        )
        self.uniform_size_checkbox.pack(side=tk.LEFT, padx=(0, 5))

        # Frame for the options that appear/disappear
        self.size_options_inner_frame = ctk.CTkFrame(size_option_outer_frame, fg_color="transparent")
        self.size_options_inner_frame.pack(side=tk.LEFT, fill=tk.X, expand=True)  # Pack inside outer frame

        ctk.CTkLabel(self.size_options_inner_frame, text="统一为").pack(side=tk.LEFT, padx=5)
        self.size_option = tk.StringVar(value="第一页尺寸")
        size_dropdown = ctk.CTkOptionMenu(
            self.size_options_inner_frame,
            values=[
                "第一页尺寸", "指定PDF尺寸", "A4标准", "自动适应最大",
                "第一页尺寸 (图像)", "指定PDF尺寸 (图像)", "A4标准 (图像)", "自动适应最大 (图像)"
            ],
            variable=self.size_option,
            command=self.update_size_options,
            width=140
        )
        size_dropdown.pack(side=tk.LEFT, padx=5)

        # "指定PDF"选择框（初始隐藏, pack managed by update_size_options)
        self.reference_pdf_frame = ctk.CTkFrame(self.size_options_inner_frame, fg_color="transparent")
        # self.reference_pdf_frame.pack(...) # Managed dynamically

        ctk.CTkLabel(self.reference_pdf_frame, text="参考PDF:").pack(side=tk.LEFT, padx=(10, 2))
        self.reference_pdf_index = tk.StringVar(value="1")
        self.reference_pdf_dropdown = ctk.CTkOptionMenu(
            self.reference_pdf_frame,
            values=["-"],
            variable=self.reference_pdf_index,
            width=80,
            dynamic_resizing=False
        )
        self.reference_pdf_dropdown.pack(side=tk.LEFT)
        # Ensure initial states are correct
        self.update_size_options(self.size_option.get())
        self.toggle_size_options_visibility()

        # --- Row 2: 输出设置区域 ---
        # Use another transparent frame for better grouping within the grid row
        output_outer_frame = ctk.CTkFrame(content_frame, fg_color="transparent")
        output_outer_frame.grid(row=2, column=0, columnspan=2, pady=5, padx=5, sticky="ew")
        output_outer_frame.grid_columnconfigure(1, weight=1)  # Allow entry to expand

        # Output Directory
        ctk.CTkLabel(output_outer_frame, text="输出目录：").grid(row=0, column=0, padx=(0, 5), pady=5, sticky="w")
        self.merge_output_path = tk.StringVar()
        merge_output_entry = ctk.CTkEntry(output_outer_frame, textvariable=self.merge_output_path)
        merge_output_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
        ctk.CTkButton(output_outer_frame, text="选择", command=self.browse_merge_output, width=60).grid(
            row=0, column=2, padx=5, pady=5, sticky="e")

        # Output Filename (conditionally shown via toggle_merge_mode_ui)
        self.merge_name_frame = ctk.CTkFrame(output_outer_frame, fg_color="transparent")
        self.merge_name_frame.grid(row=1, column=0, columnspan=3, pady=5,
                                   sticky="ew")  # Place within the output_outer_frame
        self.merge_name_frame.grid_columnconfigure(1, weight=1)

        ctk.CTkLabel(self.merge_name_frame, text="输出PDF名：").grid(row=0, column=0, padx=(0, 5), pady=5, sticky="w")
        # Inner frame for entry + .pdf label
        name_subframe = ctk.CTkFrame(self.merge_name_frame, fg_color="transparent")
        name_subframe.grid(row=0, column=1, columnspan=2, padx=0, pady=0, sticky="ew")
        name_subframe.grid_columnconfigure(0, weight=1)
        self.merge_name_entry = ctk.CTkEntry(name_subframe)
        self.merge_name_entry.grid(row=0, column=0, sticky="ew")
        self.merge_name_entry.insert(0, "合并文件")
        ctk.CTkLabel(name_subframe, text=".pdf").grid(row=0, column=1, padx=(2, 0))
        # Initial visibility managed by update_merge_file_list -> toggle_merge_mode_ui

        # --- Row 3: 进度与状态 ---
        self.merge_progress = ctk.CTkProgressBar(content_frame)
        self.merge_progress.grid(row=3, column=0, columnspan=2, padx=5, pady=(10, 2), sticky="ew")
        self.merge_progress.set(0)

        self.merge_status = ctk.CTkLabel(content_frame, text="准备就绪")
        self.merge_status.grid(row=3, column=0, columnspan=2, padx=5, pady=2,
                               sticky="ew")  # Overlaps slightly below progress

        # --- Row 4: 操作按钮 ---
        self.merge_btn = ctk.CTkButton(
            content_frame,
            text="开始合并",
            command=self.start_merge_pdfs,
            width=200
        )
        self.merge_btn.grid(row=4, column=0, columnspan=2, pady=20)  # Span 2 columns, center

    def create_img_to_pdf_widgets(self):
        """创建图片转PDF标签页的控件"""
        # 配置网格权重
        self.tab_img_to_pdf.grid_columnconfigure(0, weight=1)
        self.tab_img_to_pdf.grid_rowconfigure(1, weight=1)  # 让主框架扩展

        # 标题
        self.img_title_label = ctk.CTkLabel(
            self.tab_img_to_pdf,
            text="批量图片转PDF",
            font=("微软雅黑", 24, "bold")
        )
        self.img_title_label.grid(row=0, column=0, pady=20, sticky="n")

        # 主框架 (所有控件放这里)
        main_frame = ctk.CTkFrame(self.tab_img_to_pdf)
        main_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        main_frame.grid_columnconfigure(0, weight=1)  # Make content expand horizontally
        main_frame.grid_rowconfigure(3, weight=1)  # 让列表框扩展

        # --- Row 0: 转换模式选择 ---
        # Use a transparent inner frame to pack radio buttons horizontally
        mode_outer_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
        mode_outer_frame.grid(row=0, column=0, pady=5, padx=5, sticky="ew")

        mode_label = ctk.CTkLabel(mode_outer_frame, text="转换模式：")
        mode_label.pack(side=tk.LEFT, padx=(0, 10))

        self.conversion_mode = tk.StringVar(value="single")  # Default: merge into one PDF
        single_mode = ctk.CTkRadioButton(
            mode_outer_frame,
            text="多个图片合并为单个PDF",
            variable=self.conversion_mode,
            value="single",
            command=self.toggle_img_options
        )
        single_mode.pack(side=tk.LEFT, padx=10)

        batch_mode = ctk.CTkRadioButton(
            mode_outer_frame,
            text="每张图片单独转换PDF",
            variable=self.conversion_mode,
            value="batch",
            command=self.toggle_img_options
        )
        batch_mode.pack(side=tk.LEFT, padx=10)

        # --- Row 1: 尺寸选项框架 (仅单模式可见) ---
        # Use a transparent inner frame to pack radio buttons horizontally
        self.sizing_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
        self.sizing_frame.grid(row=1, column=0, pady=5, padx=5, sticky="ew")
        # Visibility controlled by toggle_img_options

        sizing_label = ctk.CTkLabel(self.sizing_frame, text="合并尺寸:")
        sizing_label.pack(side=tk.LEFT, padx=(0, 10))

        self.img_sizing_mode = tk.StringVar(value="original")  # Default changed to original
        size_options = [
            ("保留原尺寸", "original"),             # Moved to first for visual order
            ("统一尺寸(匹配第一张)", "match_first"),
            ("统一尺寸(A4)", "a4")
        ]
        for text, value in size_options:
            rb = ctk.CTkRadioButton(
                self.sizing_frame,
                text=text,
                variable=self.img_sizing_mode,
                value=value
            )
            rb.pack(side=tk.LEFT, padx=10)

        # --- Row 2: 文件/目录选择按钮 ---
        # Use another transparent frame for horizontal button layout
        selection_outer_frame = ctk.CTkFrame(main_frame, fg_color="transparent")
        selection_outer_frame.grid(row=2, column=0, pady=5, padx=5, sticky="ew")
        # Center the buttons within this frame (optional, using pack)
        selection_inner_frame = ctk.CTkFrame(selection_outer_frame, fg_color="transparent")
        selection_inner_frame.pack()  # Pack inner frame to center buttons

        self.select_images_btn = ctk.CTkButton(
            selection_inner_frame,  # Place button in inner frame
            text="选择图片文件(可多选)",
            command=self.select_images,
            width=180
        )
        self.select_images_btn.pack(side=tk.LEFT, padx=5, pady=5)

        self.select_pdf_output_btn = ctk.CTkButton(
            selection_inner_frame,  # Place button in inner frame
            text="选择输出PDF文件",  # Text will be updated by toggle_img_options
            command=self.select_pdf_output,
            width=180
        )
        self.select_pdf_output_btn.pack(side=tk.LEFT, padx=5, pady=5)

        # --- Row 3: 图片列表框 ---
        self.image_listbox = ctk.CTkTextbox(
            main_frame,
            height=200  # Initial height, will expand
        )
        self.image_listbox.grid(row=3, column=0, pady=10, padx=5, sticky="nsew")  # Listbox now in row 3
        self.image_listbox.configure(state="disabled")

        # --- Row 4: 进度条 ---
        self.img_progress_bar = ctk.CTkProgressBar(main_frame)
        self.img_progress_bar.grid(row=4, column=0, padx=5, pady=(10, 2), sticky="ew")  # Progress in row 4
        self.img_progress_bar.set(0)

        # --- Row 5: 状态标签 ---
        self.img_status_label = ctk.CTkLabel(main_frame, text="准备就绪")
        self.img_status_label.grid(row=5, column=0, padx=5, pady=2, sticky="ew")  # Status in row 5

        # --- Row 6: 转换按钮 ---
        self.img_convert_btn = ctk.CTkButton(
            main_frame,
            text="开始转换",
            command=self.start_img_to_pdf_conversion,
            width=200
        )
        self.img_convert_btn.grid(row=6, column=0, pady=20)  # Convert button in row 6

        # Ensure initial UI state is correct based on default mode
        self.toggle_img_options()

    # ------------------------------------------------------------------
    # Word ➜ PDF 标签页控件
    # ------------------------------------------------------------------

    def create_word2pdf_widgets(self):
        """创建 Word 批量转 PDF 页面控件"""
        # 配置列权重，使内容水平居中
        self.tab_word2pdf.grid_columnconfigure(0, weight=1)

        # 标题
        title_label = ctk.CTkLabel(
            self.tab_word2pdf,
            text="Word批量转PDF",
            font=("微软雅黑", 24, "bold"),
        )
        title_label.grid(row=0, column=0, pady=20)

        # 主框架
        main_frame = ctk.CTkFrame(self.tab_word2pdf)
        main_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        main_frame.grid_columnconfigure(0, weight=1)

        # 选择文件按钮
        select_word_btn = ctk.CTkButton(
            main_frame,
            text="选择Word文件(可多选)",
            command=self.select_word_files,
            width=200,
        )
        select_word_btn.grid(row=0, column=0, pady=10)

        # 选择输出目录按钮
        select_output_btn = ctk.CTkButton(
            main_frame,
            text="选择输出目录",
            command=self.select_word_output_folder,
            width=200,
        )
        select_output_btn.grid(row=1, column=0, pady=10)

        # 文件列表框
        self.word_file_listbox = ctk.CTkTextbox(main_frame, height=150, width=500)
        self.word_file_listbox.grid(row=2, column=0, pady=10, padx=20)
        self.word_file_listbox.configure(state="disabled")

        # 进度条
        self.word_progress_bar = ctk.CTkProgressBar(main_frame)
        self.word_progress_bar.grid(row=3, column=0, pady=10, padx=20, sticky="ew")
        self.word_progress_bar.set(0)

        # 状态标签
        self.word_status_label = ctk.CTkLabel(main_frame, text="准备就绪")
        self.word_status_label.grid(row=4, column=0, pady=5)

        # 开始转换按钮
        self.word_convert_btn = ctk.CTkButton(
            main_frame,
            text="开始转换",
            command=self.start_word2pdf_conversion,
            width=200,
        )
        self.word_convert_btn.grid(row=5, column=0, pady=20)

    # ===============================================
    # ===== 新增：水印功能 Widgets 和方法 =========
    # ===============================================

    def create_watermark_widgets(self):
        """创建添加水印标签页的控件"""
        # 配置网格权重
        self.tab_watermark.grid_columnconfigure(0, weight=1)
        self.tab_watermark.grid_rowconfigure(1, weight=1)  # 让主框架扩展

        # 标题
        wm_title = ctk.CTkLabel(self.tab_watermark, text="批量添加水印", font=("微软雅黑", 24, "bold"))
        wm_title.grid(row=0, column=0, pady=20, sticky="n")

        # 主内容框架 (保留背景色)
        main_frame = ctk.CTkFrame(self.tab_watermark)
        main_frame.grid(row=1, column=0, padx=20, pady=10, sticky="nsew")
        main_frame.grid_columnconfigure(0, weight=1)
        main_frame.grid_rowconfigure(1, weight=1)  # 让文件列表扩展

        # --- 文件选择区域 (使用透明框架包裹) ---
        file_select_frame = ctk.CTkFrame(main_frame, fg_color="transparent") # 设置透明
        file_select_frame.grid(row=0, column=0, pady=5, sticky="ew")
        # Widgets packed inside the transparent frame
        ctk.CTkButton(file_select_frame, text="选择目标PDF(可多选)", command=self.select_watermark_pdfs,
                      width=180).pack(side=tk.LEFT, padx=5, pady=5)
        ctk.CTkButton(file_select_frame, text="选择水印文件(图片/PDF)", command=self.select_watermark_file,
                      width=180).pack(side=tk.LEFT, padx=5, pady=5)
        self.watermark_file_label = ctk.CTkLabel(file_select_frame, text="水印文件: (未选择)", wraplength=300,
                                                 justify="left")
        self.watermark_file_label.pack(side=tk.LEFT, padx=10, pady=5, fill=tk.X, expand=True)

        # --- PDF 文件列表 (直接放在main_frame) ---
        self.watermark_pdf_listbox = ctk.CTkTextbox(main_frame, height=150)
        self.watermark_pdf_listbox.grid(row=1, column=0, padx=5, pady=5, sticky="nsew")
        self.watermark_pdf_listbox.insert("1.0", "目标 PDF 文件列表:\n(未选择)")
        self.watermark_pdf_listbox.configure(state="disabled")

        # --- 水印参数设置 (使用透明框架包裹) ---
        settings_frame = ctk.CTkFrame(main_frame, fg_color="transparent") # 设置透明
        settings_frame.grid(row=2, column=0, pady=10, sticky="ew")
        settings_frame.grid_columnconfigure(1, weight=1)  # Allow sliders/options to expand if needed
        settings_frame.grid_columnconfigure(4, weight=1) # Adjusted column index for expansion

        # Widgets gridded inside the transparent frame
        ctk.CTkLabel(settings_frame, text="不透明度:").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.wm_opacity_slider = ctk.CTkSlider(settings_frame, from_=0.0, to=1.0, variable=self.watermark_opacity,
                                               command=self.update_wm_opacity_label)
        self.wm_opacity_slider.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
        self.wm_opacity_label = ctk.CTkLabel(settings_frame, text=f"{int(self.watermark_opacity.get() * 100)}%")
        self.wm_opacity_label.grid(row=0, column=2, padx=(0, 15), pady=5, sticky="w")

        ctk.CTkLabel(settings_frame, text="缩放比例:").grid(row=0, column=3, padx=5, pady=5, sticky="w")
        self.wm_scale_slider = ctk.CTkSlider(settings_frame, from_=0.1, to=2.0, variable=self.watermark_scale,
                                             command=self.update_wm_scale_label)  # 10% to 200%
        self.wm_scale_slider.grid(row=0, column=4, padx=5, pady=5, sticky="ew")
        self.wm_scale_label = ctk.CTkLabel(settings_frame, text=f"{int(self.watermark_scale.get() * 100)}%")
        self.wm_scale_label.grid(row=0, column=5, padx=(0, 5), pady=5, sticky="w")

        ctk.CTkLabel(settings_frame, text="旋转角度:").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.wm_rotate_slider = ctk.CTkSlider(settings_frame, from_=0, to=360, variable=self.watermark_rotation,
                                              command=self.update_wm_rotate_label)
        self.wm_rotate_slider.grid(row=1, column=1, padx=5, pady=5, sticky="ew")
        self.wm_rotate_label = ctk.CTkLabel(settings_frame, text=f"{self.watermark_rotation.get()}°")
        self.wm_rotate_label.grid(row=1, column=2, padx=(0, 15), pady=5, sticky="w")

        ctk.CTkLabel(settings_frame, text="放置位置:").grid(row=1, column=3, padx=5, pady=5, sticky="w")
        wm_position_menu = ctk.CTkOptionMenu(settings_frame, values=["居中", "左上", "右上", "左下", "右下", "平铺"],
                                             variable=self.watermark_position)
        wm_position_menu.grid(row=1, column=4, columnspan=2, padx=5, pady=5, sticky="ew")

        ctk.CTkLabel(settings_frame, text="图层:").grid(row=2, column=0, padx=5, pady=5, sticky="w")
        wm_layer_switch = ctk.CTkSwitch(settings_frame, text="置于顶层(覆盖内容)", variable=self.watermark_layer,
                                        onvalue=True, offvalue=False)
        wm_layer_switch.grid(row=2, column=1, columnspan=2, padx=5, pady=5, sticky="w")

        # --- 输出设置 (使用透明框架包裹) ---
        output_frame = ctk.CTkFrame(main_frame, fg_color="transparent") # 设置透明
        output_frame.grid(row=3, column=0, pady=10, sticky="ew")
        output_frame.grid_columnconfigure(1, weight=1)  # Let entry expand

        # Widgets gridded inside the transparent frame
        ctk.CTkLabel(output_frame, text="输出目录：").grid(row=0, column=0, padx=5, pady=5, sticky="w")
        self.watermark_output_entry = ctk.CTkEntry(output_frame)  # textvariable can be set later if needed
        self.watermark_output_entry.grid(row=0, column=1, padx=5, pady=5, sticky="ew")
        ctk.CTkButton(output_frame, text="选择", command=self.select_watermark_output_folder, width=60).grid(row=0,
                                                                                                             column=2,
                                                                                                             padx=5,
                                                                                                             pady=5)

        ctk.CTkLabel(output_frame, text="输出后缀：").grid(row=1, column=0, padx=5, pady=5, sticky="w")
        self.watermark_suffix_entry = ctk.CTkEntry(output_frame,
                                                   placeholder_text="例如: _watermarked (留空则可能覆盖原文件)")
        self.watermark_suffix_entry.grid(row=1, column=1, columnspan=2, padx=5, pady=5, sticky="ew")
        self.watermark_suffix_entry.insert(0, "_watermarked")

        # --- 进度与状态 (使用透明框架包裹) ---
        status_frame = ctk.CTkFrame(main_frame, fg_color="transparent") # 设置透明
        status_frame.grid(row=4, column=0, pady=10, sticky="ew")
        status_frame.grid_columnconfigure(0, weight=1)

        # Widgets gridded inside the transparent frame
        self.watermark_progress_bar = ctk.CTkProgressBar(status_frame)
        self.watermark_progress_bar.grid(row=0, column=0, padx=5, pady=5, sticky="ew")
        self.watermark_progress_bar.set(0)

        self.watermark_status_label = ctk.CTkLabel(status_frame, text="准备就绪")
        self.watermark_status_label.grid(row=1, column=0, padx=5, pady=2, sticky="ew")

        # --- 操作按钮 (使用透明框架包裹) ---
        action_frame = ctk.CTkFrame(main_frame, fg_color="transparent") # 设置透明
        action_frame.grid(row=5, column=0, pady=10)  # Center button

        # Widget packed inside the transparent frame
        self.watermark_btn = ctk.CTkButton(action_frame, text="开始添加水印", command=self.start_watermarking,
                                           width=200)
        self.watermark_btn.pack(pady=10)

